package com.course.app.biz;

import com.course.app.api.data.LearnStatDTO;
import com.course.app.transformer.LearnStatTransformer;
import com.course.domain.model.CourseInfo;
import com.course.domain.model.LearnStat;
import com.course.domain.model.Student;
import com.course.domain.service.CourseService;
import com.course.domain.service.LearnService;
import com.course.domain.service.UserService;
import com.course.util.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

/**
 * Created by Justin on 2017/7/1.
 */
@Component
public class LearnBiz {

    private final UserService userService;
    private final LearnService learnService;
    private final CourseService courseService;

    @Autowired
    public LearnBiz(UserService userService, LearnService learnService, CourseService courseService) {
        this.userService = userService;
        this.learnService = learnService;
        this.courseService = courseService;
    }

    public LearnStatDTO loadStat(int studentId, LocalDate today) {
        Student student = userService.loadStudent(studentId);
        if (student == null) {
            return null;
        }
        int courseId = student.getCourseId();
        if (courseId == 0) {
            return null;
        }
        CourseInfo info = courseService.loadInfo(courseId);
        LocalDate begin = DateUtils.toLocalDate(info.getBeginDate());
        int weekIdx = DateUtils.calcWeekIdx(begin, today);
        int weekDay = DateUtils.calcWeekDay(begin, today);
        LearnStat learnStat = learnService.loadStat(studentId, courseId, weekIdx, weekDay);
        if (learnStat == null) {
            return null;
        }
        return LearnStatTransformer.toDTO(learnStat);
    }

    public boolean record(int studentId, int groupId) {
        Student student = userService.loadStudent(studentId);
        if (student == null) {
            return false;
        }
        int courseId = student.getCourseId();
        if (courseId == 0) {
            return false;
        }
        try {
            boolean success = learnService.doneRecord(studentId, courseId, groupId);
            student.setScore(student.getScore() + 1);
            userService.updateStudent(student);
            return success;
        } catch (Exception e) {
            return false;
        }
    }
}
